<template>
  <el-dialog
    v-bind="$attrs"
    width="1000px"
    :title="dialogForm.id ? '修改' : '新增'"
    center
  >
    <el-form
      ref="dialogFormRef"
      :model="dialogForm"
      :rules="rules"
      label-width="auto"
      :disabled="isDetail"
    >
      <el-form-item label="视频名称" prop="title">
        <el-input v-model="dialogForm.title" />
      </el-form-item>
      <!-- <el-form-item label="介绍" prop="introduction">
        <el-input v-model="dialogForm.introduction" type="textarea" :rows="5" />
      </el-form-item> -->
      <el-form-item label="栏目" prop="vcolumn">
        <el-select v-model="dialogForm.vcolumn">
          <el-option label="质量基础课程公益培训视频" value="zljckcgypxsp" />
          <el-option
            label="历年政府质量奖经验分享视频/手册"
            value="lnzfzljjyfxsp"
          />
          <el-option label="检验检测云课堂-培训视频" value="jyjcpxsp" />
        </el-select>
      </el-form-item>
      <el-form-item label="视频" prop="fileList" v-if="!dialogForm.id">
        <CMSFileUpload
          v-model:value="dialogForm.fileList"
          :limit="1"
          accept="video/*"
        />
      </el-form-item>
      <el-form-item label="视频" v-else>
        <video
          id="video"
          ref="videoPlayer"
          style="width: 400px; height: 225px"
          controls
        ></video>
      </el-form-item>
      <el-form-item label="是否发布" prop="status">
        <el-radio-group v-model="dialogForm.status">
          <el-radio :value="1">是</el-radio>
          <el-radio :value="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onclose()">取消</el-button>
        <el-button type="primary" @click="submit(false)" v-if="isFabu"
          >保存</el-button
        >
        <el-button type="primary" @click="submit(true)" v-if="!isDetail">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import { defineComponent, reactive, ref, toRefs, watch, computed } from "vue";
import Editor from "@/components/Editor/index.vue";
import CMSFileUpload from "@/components/CMSFileUpload/index.vue";
import { addOrUpdateVideo } from "@/api/api";
import Hls from "hls.js";
export default defineComponent({
  components: { Editor, CMSFileUpload },
  props: {
    dataForm: Object,
    isDetail: {
      type: Boolean,
      default: false,
    },
    isFabu: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, { emit }) {
    const videoPlayer = ref(null);
    const dialogFormRef = ref();
    let hls = null;
    const dataMap = reactive({
      dialogForm: {},
      rules: {
        exerciseName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        label: [{ required: true, message: "请输入标签", trigger: "blur" }],
        exerciseTime: [
          { required: true, message: "请选择活动时间", trigger: "change" },
        ],
        exerciseContent: [
          { required: true, message: "请输入活动内容", trigger: "blur" },
        ],
        departName: [
          { required: true, message: "请输入发布部门", trigger: "blur" },
        ],
        isPublish: [
          { required: true, message: "请选择是否发布", trigger: "change" },
        ],
      },
      videoOptions: {
        src: "",
        controls: true, // 显示控制条
        autoplay: false, // 禁止自动播放（避免浏览器限制）
        loop: false, // 循环播放
        volume: 0.5, // 默认音量
        poster: "",
        type: "m3u8",
      },
    });
    const methodsMap = reactive({
      onclose() {
        emit("close");
      },
      submit(flag) {
        console.log(dataMap.dialogForm);
        dialogFormRef.value.validate((valid) => {
          if (valid) {
            let params = {
              ...dataMap.dialogForm,
            };
            if (!params.id) {
              params.videoFile = dataMap.dialogForm.fileList[0];
            }
            delete params.fileList;
            addOrUpdateVideo(params).then((res) => {
              console.log("新增成功", Date.now());
              setTimeout(() => {
                emit("getDatas");
                emit("close");
              }, 500);
            });
          } else {
            return false;
          }
        });
      },
    });
    onMounted(() => {
      let defaultData = {
        exerciseContent: "",
        exerciseTime: [],
      };
      if (props.dataForm) {
        let temp = JSON.parse(JSON.stringify(props.dataForm));

        dataMap.dialogForm = {
          ...defaultData,
          ...temp,
        };
        const m3u8Url =
          import.meta.env.VITE_API_PATH_FULL +
          `/stream/${props.dataForm.id}/index.m3u8`;
        // const m3u8Url = "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8"

        nextTick(() => {
          // 兼容性检查
          if (Hls.isSupported() && videoPlayer.value) {
            hls = new Hls();
            hls.loadSource(m3u8Url);
            hls.attachMedia(videoPlayer.value);

            // 可选：监听错误事件
            hls.on(Hls.Events.ERROR, (event, data) => {
              console.error("HLS 错误:", data);
            });
          } else if (
            videoPlayer.value.canPlayType("application/vnd.apple.mpegurl")
          ) {
            // Safari 等原生支持 HLS 的浏览器
            videoPlayer.value.src = m3u8Url;
          }
        });
      } else {
        dataMap.dialogForm = {
          ...defaultData,
        };
      }
    });
    // 清理资源
    onUnmounted(() => {
      if (hls) {
        hls.destroy();
      }
    });
    return {
      ...toRefs(dataMap),
      ...toRefs(methodsMap),
      dialogFormRef,
      videoPlayer,
    };
  },
});
</script>
